package com.web.exiaodao.remote.service.impl;

import com.web.exiaodao.business.entity.MomentsInteraction;
import com.web.exiaodao.remote.service.ApiUserService;
import com.web.exiaodao.remote.vo.MomentsInteractionVo;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

import com.web.exiaodao.remote.vo.UserVo;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.web.exiaodao.business.repository.MomentsInteractionRepository;
import com.web.exiaodao.remote.service.ApiMomentsInteractionService;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.util.jpa.DynamicSpecifications;
import com.web.webstart.base.util.jpa.SearchFilter;
import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.util.jpa.SearchFilter.Operator;
import com.web.webstart.base.util.result.XaResult;
import com.web.webstart.base.util.XaUtil;

/**
 * @author: zhangl
 * @times: 2016-11-10 14:29:16
 * 类的说明：前端APIMomentsInteraction接口实现类
 **/
@Service("ApiMomentsInteractionService")
@Transactional(readOnly = false)
public class ApiMomentsInteractionServiceImpl extends BaseService<MomentsInteraction> implements ApiMomentsInteractionService{

	private static final Logger LOGGER = Logger.getLogger(ApiMomentsInteractionServiceImpl.class);

	@Autowired
	MomentsInteractionRepository momentsInteractionRepository;
	@Autowired
	private ApiUserService userService;


	@Override
	public XaResult<MomentsInteractionVo> findOne(Long tId) throws BusinessException {
		MomentsInteraction obj = momentsInteractionRepository.findByIdAndStatusNot(tId,XaConstant.Status.delete);
		XaResult<MomentsInteractionVo> xr = new XaResult<MomentsInteractionVo>();
		if (XaUtil.isNotEmpty(obj)) {
			xr.setObject(JSON.parseObject(JSON.toJSONString(obj),MomentsInteractionVo.class));
			xr.getObject().setId(obj.getId());
			LOGGER.info("查询单个实体----->MomentsInteraction");
		} else {
			xr.error(XaConstant.Message.object_not_find);
			LOGGER.info(XaConstant.Message.object_not_find);
		}
		return xr;
	}

	@Override
	public XaResult<MomentsInteractionVo> findLastOne() throws BusinessException {
		XaResult<MomentsInteractionVo> xr = new XaResult<>();
		Map<String, SearchFilter> filters = new HashMap<>();
			filters.put("status", new SearchFilter("status", Operator.NE, XaConstant.Status.delete));
			List<MomentsInteraction> entitys = momentsInteractionRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), MomentsInteraction.class), new Sort(
				new Sort.Order[]{
				new Sort.Order(Sort.Direction.DESC, "createTime"),
				new Sort.Order(Sort.Direction.DESC, "id")
				}));
				if (entitys == null || entitys.size() == 0) {
				xr.error("暂无信息");
				} else {
				xr.setObject(JSON.parseObject(JSON.toJSONString(entitys.get(0)), MomentsInteractionVo.class));
				xr.getObject().setId(entitys.get(0).getId());
				LOGGER.info("查询单个实体----->MomentsInteraction");
			}
		return xr;
	}

	@Override
	public XaResult<List<MomentsInteractionVo>> findListNEStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable)
			throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示非删除的所有数据
			status = XaConstant.Status.delete;
		}
		filters.put("status", new SearchFilter("status", Operator.NE, status));
		Page<MomentsInteraction> page = momentsInteractionRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), MomentsInteraction.class), pageable);
		XaResult<List<MomentsInteractionVo>> xr = new XaResult<List<MomentsInteractionVo>>();
		xr.setObject(JSON.parseArray(JSON.toJSONString(page.getContent()), MomentsInteractionVo.class));
		for(int i=0;i<page.getContent().size();i++){
			xr.getObject().get(i).setId(page.getContent().get(i).getId());
		}
		return xr;
	}

	@Override
	public XaResult<List<MomentsInteractionVo>> findListEQStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable)
			throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示正常数据
			status = XaConstant.Status.valid;
		}
		filters.put("status", new SearchFilter("status", Operator.EQ, status));
		Page<MomentsInteraction> page = momentsInteractionRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), MomentsInteraction.class), pageable);
		XaResult<List<MomentsInteractionVo>> xr = new XaResult<List<MomentsInteractionVo>>();
		xr.setObject(JSON.parseArray(JSON.toJSONString(page.getContent()), MomentsInteractionVo.class));
		for(int i=0;i<page.getContent().size();i++){
			xr.getObject().get(i).setId(page.getContent().get(i).getId());
		}
		return xr;
	}

	@Override
	public XaResult<MomentsInteractionVo> multiOperate(String modelIds,
			Integer status) throws BusinessException {
		XaResult<MomentsInteractionVo> xr = new XaResult<MomentsInteractionVo>();
		if(status == null){
			status = XaConstant.Status.delete;
		}
		if(modelIds != null){
			String[] ids = modelIds.split(",");
			for(String id : ids){
				MomentsInteraction obj = momentsInteractionRepository.findByIdAndStatusNot(Long.parseLong(id),status);
				if (XaUtil.isNotEmpty(obj)) {
					obj.setStatus(status);
					obj = momentsInteractionRepository.save(obj);
					xr.setObject(JSON.parseObject(JSON.toJSONString(obj), MomentsInteractionVo.class));
					xr.getObject().setId(obj.getId());
				}
			}
		}
		LOGGER.info("更改数据状态----->MomentsInteraction");
		return xr;
	}

	@Override
	public XaResult<MomentsInteractionVo> createModel(MomentsInteraction model)
			throws BusinessException {
		XaResult<MomentsInteractionVo> xr = new XaResult<MomentsInteractionVo>();

		MomentsInteraction obj = momentsInteractionRepository.save(model);
		xr.setObject(JSON.parseObject(JSON.toJSONString(obj), MomentsInteractionVo.class));
		xr.getObject().setId(obj.getId());

		XaResult<UserVo> userXr =  userService.findOne(obj.getUserId());
		xr.getObject().setUserName(userXr.getObject().getUserName());

		if (XaUtil.isNotEmpty(obj.getReplyToUserId())) {
			XaResult<UserVo> userXr2 =  userService.findOne(obj.getReplyToUserId());
			xr.getObject().setReplyToUserName(userXr2.getObject().getUserName());
		}

		LOGGER.info("新增数据成功----->MomentsInteraction");
		return xr;
	}

	@Override
	public XaResult<MomentsInteractionVo> updateModel(MomentsInteraction model)
			throws BusinessException {
		MomentsInteraction obj = momentsInteractionRepository.findOne(model.getId());
		XaResult<MomentsInteractionVo> xr = new XaResult<MomentsInteractionVo>();
		if (XaUtil.isNotEmpty(obj)) {
					obj.setType(XaUtil.isNotEmpty(model.getType()) ? model.getType() : obj.getType());
					obj.setUserId(XaUtil.isNotEmpty(model.getUserId()) ? model.getUserId() : obj.getUserId());
					obj.setReplyToUserId(XaUtil.isNotEmpty(model.getReplyToUserId()) ? model.getReplyToUserId() : obj.getReplyToUserId());
					obj.setContent(XaUtil.isNotEmpty(model.getContent()) ? model.getContent() : obj.getContent());
					obj.setMomentId(XaUtil.isNotEmpty(model.getMomentId()) ? model.getMomentId() : obj.getMomentId());
				obj = momentsInteractionRepository.save(obj);
			xr.setObject(JSON.parseObject(JSON.toJSONString(obj), MomentsInteractionVo.class));
			xr.getObject().setId(obj.getId());
		} else {
			xr.error(XaConstant.Message.object_not_find);
		}
		LOGGER.info("编辑数据成功----->MomentsInteraction");
		return xr;
	}

	//取消点赞
	@Override
	public XaResult<Boolean> cancelLike(String userId, Long momentId) {
		XaResult<Boolean> xr = new XaResult<Boolean>();
		MomentsInteraction wis = momentsInteractionRepository.findByMomentIdAndTypeAndUserId(momentId+"", 1, Long.parseLong(userId));
		if(XaUtil.isNotEmpty(wis)){
			momentsInteractionRepository.delete(wis);
			xr.setObject(true);
		}else{
			xr.error("您还没有点赞！");
		}
		return xr;
	}

	@Override
	public XaResult<Boolean> isLike(String userId, Long momentId) {
		XaResult<Boolean> xr = new XaResult<Boolean>();
        MomentsInteraction wis = momentsInteractionRepository.findByMomentIdAndTypeAndUserId(momentId+"",  1, org.apache.commons.lang3.math.NumberUtils.toLong(userId));
		if(XaUtil.isNotEmpty(wis)){
			xr.setObject(true);
		}else{
			xr.setObject(false);
		}
		return xr;
	}

	//删除评论
	@Override
	public XaResult<MomentsInteractionVo> deleteMomentInteraction(
			String modelIds, Integer status, String userId) {
		XaResult<MomentsInteractionVo> xr = new XaResult<MomentsInteractionVo>();
		if(status == null){
			status = XaConstant.Status.delete;
		}
		if(modelIds != null){
			String[] ids = modelIds.split(",");
			for(String id : ids){
				MomentsInteraction obj = momentsInteractionRepository.findByIdAndStatusNot(Long.parseLong(id),status);
				if (XaUtil.isNotEmpty(obj)) {
					if(!(obj.getUserId()+"").equals(userId)){
						xr.error("只能删除自己发的评论！");
						return xr;
					}
					obj.setStatus(status);
					obj = momentsInteractionRepository.save(obj);
					xr.setObject(JSON.parseObject(JSON.toJSONString(obj), MomentsInteractionVo.class));
					xr.getObject().setId(obj.getId());
				} else {
					xr.error(XaConstant.Message.object_not_find);
				}
			}
		}
		LOGGER.info("更改数据状态----->WorkGroup");
		return xr;
	}

}
